<template>
  <div class="library-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">书库</h1>
      <p class="page-subtitle">发现更多精彩小说</p>
    </div>

    <!-- 筛选条件区域 -->
    <div class="filter-section">
      <div class="filter-container">
        <!-- 分类筛选 -->
        <div class="filter-group">
          <label class="filter-label">分类:</label>
          <div class="filter-options">
            <el-button
              v-for="cat in categories"
              :key="cat.key"
              :type="selectedCategory === cat.key ? 'primary' : ''"
              :plain="selectedCategory !== cat.key"
              size="small"
              @click="selectCategory(cat.key)"
            >
              {{ cat.label }}
            </el-button>
          </div>
        </div>

        <!-- 状态筛选 -->
        <div class="filter-group">
          <label class="filter-label">状态:</label>
          <div class="filter-options">
            <el-button
              v-for="status in statusOptions"
              :key="status.key"
              :type="selectedStatus === status.key ? 'primary' : ''"
              :plain="selectedStatus !== status.key"
              size="small"
              @click="selectStatus(status.key)"
            >
              {{ status.label }}
            </el-button>
          </div>
        </div>

        <!-- 字数筛选 -->
        <div class="filter-group">
          <label class="filter-label">字数:</label>
          <div class="filter-options">
            <el-button
              v-for="range in wordCountRanges"
              :key="range.key"
              :type="selectedWordCount === range.key ? 'primary' : ''"
              :plain="selectedWordCount !== range.key"
              size="small"
              @click="selectWordCount(range.key)"
            >
              {{ range.label }}
            </el-button>
          </div>
        </div>

        <!-- VIP筛选 -->
        <div class="filter-group">
          <label class="filter-label">类型:</label>
          <div class="filter-options">
            <el-button
              v-for="vip in vipOptions"
              :key="vip.key"
              :type="selectedVip === vip.key ? 'primary' : ''"
              :plain="selectedVip !== vip.key"
              size="small"
              @click="selectVip(vip.key)"
            >
              {{ vip.label }}
            </el-button>
          </div>
        </div>

        <!-- 标签筛选 -->
        <div class="filter-group">
          <label class="filter-label">标签:</label>
          <div class="filter-options">
            <el-select
              v-model="selectedTags"
              multiple
              placeholder="选择标签"
              size="small"
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
              style="width: 200px"
            >
              <el-option
                v-for="tag in availableTags"
                :key="tag"
                :label="tag"
                :value="tag"
              />
            </el-select>
          </div>
        </div>

        <!-- 排序方式 -->
        <div class="filter-group">
          <label class="filter-label">排序:</label>
          <div class="filter-options">
            <el-select v-model="sortBy" size="small" style="width: 120px">
              <el-option
                v-for="sort in sortOptions"
                :key="sort.key"
                :label="sort.label"
                :value="sort.key"
              />
            </el-select>
          </div>
        </div>

        <!-- 重置按钮 -->
        <div class="filter-actions">
          <el-button size="small" @click="resetFilters">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索小说名称、作者、标签..."
          size="large"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
      </div>
    </div>

    <!-- 结果统计 -->
    <div class="result-stats">
      <span class="stats-text">
        找到 <strong>{{ filteredNovels.length }}</strong> 本小说
      </span>
      <!-- 视图切换 -->
      <div class="view-toggle">
        <el-button-group>
          <el-button
            :type="viewMode === 'grid' ? 'primary' : ''"
            size="small"
            @click="viewMode = 'grid'"
          >
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button
            :type="viewMode === 'list' ? 'primary' : ''"
            size="small"
            @click="viewMode = 'list'"
          >
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 小说列表 -->
    <div class="novels-section" v-loading="loading">
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="novels-grid">
        <NovelCard
          v-for="novel in paginatedNovels"
          :key="novel.id"
          :novel="novel"
        />
      </div>

      <!-- 列表视图 -->
      <div v-else class="novels-list">
        <div
          v-for="novel in paginatedNovels"
          :key="novel.id"
          class="novel-item"
          @click="goToDetail(novel.id)"
        >
          <div class="item-cover">
            <img :src="novel.cover" :alt="novel.title" />
            <div v-if="novel.isVip" class="vip-badge">VIP</div>
          </div>
          <div class="item-content">
            <h3 class="item-title">{{ novel.title }}</h3>
            <p class="item-author">{{ novel.author }}</p>
            <p class="item-desc">{{ novel.description }}</p>
            <div class="item-tags">
              <el-tag
                v-for="tag in novel.tags.slice(0, 4)"
                :key="tag"
                size="small"
                type="info"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
          <div class="item-stats">
            <div class="stat-item">
              <span class="stat-label">分类:</span>
              <span class="stat-value">{{ getCategoryLabel(novel.category) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">状态:</span>
              <span class="stat-value">{{ getStatusLabel(novel.status) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">字数:</span>
              <span class="stat-value">{{ formatWordCount(novel.wordCount) }}</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">评分:</span>
              <el-rate v-model="novel.rating" disabled size="small" />
            </div>
            <div class="stat-item">
              <span class="stat-label">更新:</span>
              <span class="stat-value">{{ formatTime(novel.updatedAt) }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="!loading && filteredNovels.length === 0" class="empty-state">
        <el-empty description="没有找到符合条件的小说">
          <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
        </el-empty>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="filteredNovels.length > 0" class="pagination-section">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[12, 24, 48, 96]"
        :total="filteredNovels.length"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { Novel, NovelCategory, NovelStatus } from '@/types'
import { useNovelStore } from '@/stores/novel'
import { useI18n } from 'vue-i18n'
import NovelCard from '@/components/NovelCard.vue'

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const novelStore = useNovelStore()

// 响应式数据
const loading = ref(false)
const viewMode = ref<'grid' | 'list'>('grid')
const currentPage = ref(1)
const pageSize = ref(24)
const searchKeyword = ref('')

// 筛选条件
const selectedCategory = ref<NovelCategory | 'all'>('all')
const selectedStatus = ref<NovelStatus | 'all'>('all')
const selectedWordCount = ref<string>('all')
const selectedVip = ref<string>('all')
const selectedTags = ref<string[]>([])
const sortBy = ref('updatedAt')

// 筛选选项配置
const categories = ref([
  { key: 'all', label: '全部' },
  { key: 'fantasy', label: '玄幻' },
  { key: 'urban', label: '都市' },
  { key: 'romance', label: '言情' },
  { key: 'historical', label: '历史' },
  { key: 'scifi', label: '科幻' },
  { key: 'mystery', label: '悬疑' },
  { key: 'military', label: '军事' },
  { key: 'game', label: '游戏' },
])

const statusOptions = ref([
  { key: 'all', label: '全部' },
  { key: 'ongoing', label: '连载中' },
  { key: 'completed', label: '已完结' },
  { key: 'paused', label: '暂停更新' },
])

const wordCountRanges = ref([
  { key: 'all', label: '不限' },
  { key: '0-100000', label: '10万字以下' },
  { key: '100000-500000', label: '10-50万字' },
  { key: '500000-1000000', label: '50-100万字' },
  { key: '1000000-99999999', label: '100万字以上' },
])

const vipOptions = ref([
  { key: 'all', label: '全部' },
  { key: 'free', label: '免费' },
  { key: 'vip', label: 'VIP' },
])

const sortOptions = ref([
  { key: 'updatedAt', label: '最新更新' },
  { key: 'rating', label: '评分最高' },
  { key: 'viewCount', label: '人气最高' },
  { key: 'favoriteCount', label: '收藏最多' },
  { key: 'wordCount', label: '字数最多' },
  { key: 'createdAt', label: '最新发布' },
])

// 计算属性
const availableTags = computed(() => novelStore.getAllTags)

const filteredNovels = computed(() => {
  let novels = [...novelStore.novels]

  // 搜索关键词过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase()
    novels = novels.filter(novel =>
      novel.title.toLowerCase().includes(keyword) ||
      novel.author.toLowerCase().includes(keyword) ||
      novel.tags.some(tag => tag.toLowerCase().includes(keyword))
    )
  }

  // 分类过滤
  if (selectedCategory.value !== 'all') {
    novels = novels.filter(novel => novel.category === selectedCategory.value)
  }

  // 状态过滤
  if (selectedStatus.value !== 'all') {
    novels = novels.filter(novel => novel.status === selectedStatus.value)
  }

  // 字数过滤
  if (selectedWordCount.value !== 'all') {
    const [min, max] = selectedWordCount.value.split('-').map(Number)
    novels = novels.filter(novel =>
      novel.wordCount >= min && novel.wordCount <= max
    )
  }

  // VIP过滤
  if (selectedVip.value !== 'all') {
    const isVip = selectedVip.value === 'vip'
    novels = novels.filter(novel => novel.isVip === isVip)
  }

  // 标签过滤
  if (selectedTags.value.length > 0) {
    novels = novels.filter(novel =>
      selectedTags.value.some(tag => novel.tags.includes(tag))
    )
  }

  // 排序
  novels.sort((a, b) => {
    switch (sortBy.value) {
      case 'rating':
        return b.rating - a.rating
      case 'viewCount':
        return b.viewCount - a.viewCount
      case 'favoriteCount':
        return b.favoriteCount - a.favoriteCount
      case 'wordCount':
        return b.wordCount - a.wordCount
      case 'createdAt':
        return new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
      case 'updatedAt':
      default:
        return new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
    }
  })

  return novels
})

const paginatedNovels = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredNovels.value.slice(start, end)
})

// 方法
const selectCategory = (category: string) => {
  selectedCategory.value = category as NovelCategory | 'all'
  currentPage.value = 1
}

const selectStatus = (status: string) => {
  selectedStatus.value = status as NovelStatus | 'all'
  currentPage.value = 1
}

const selectWordCount = (range: string) => {
  selectedWordCount.value = range
  currentPage.value = 1
}

const selectVip = (vip: string) => {
  selectedVip.value = vip
  currentPage.value = 1
}

const resetFilters = () => {
  selectedCategory.value = 'all'
  selectedStatus.value = 'all'
  selectedWordCount.value = 'all'
  selectedVip.value = 'all'
  selectedTags.value = []
  sortBy.value = 'updatedAt'
  searchKeyword.value = ''
  currentPage.value = 1
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  // 滚动到顶部
  window.scrollTo({ top: 0, behavior: 'smooth' })
}

const goToDetail = (novelId: string) => {
  router.push(`/novel/${novelId}`)
}

const getCategoryLabel = (category: NovelCategory) => {
  const cat = categories.value.find(c => c.key === category)
  return cat?.label || category
}

const getStatusLabel = (status: NovelStatus) => {
  const stat = statusOptions.value.find(s => s.key === status)
  return stat?.label || status
}

const formatWordCount = (count: number) => {
  if (count >= 10000) {
    return (count / 10000).toFixed(1) + '万字'
  }
  return count + '字'
}

const formatTime = (timeStr: string) => {
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (days === 0) {
    return '今天'
  } else if (days === 1) {
    return '昨天'
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString()
  }
}

// 初始化数据
const initData = async () => {
  try {
    loading.value = true
    await novelStore.fetchNovels()
  } catch (error) {
    ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化
watch(
  () => route.params.category,
  (newCategory) => {
    if (newCategory && newCategory !== 'all') {
      selectedCategory.value = newCategory as NovelCategory
    }
  },
  { immediate: true }
)

// 监听筛选条件变化，重置页码
watch(
  [selectedCategory, selectedStatus, selectedWordCount, selectedVip, selectedTags, sortBy],
  () => {
    currentPage.value = 1
  }
)

onMounted(() => {
  initData()
})
</script>

<style lang="scss" scoped>
.library-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: var(--spacing-lg);
}

.page-header {
  text-align: center;
  margin-bottom: var(--spacing-xl);
  
  .page-title {
    font-size: var(--font-size-3xl);
    font-weight: 700;
    color: var(--text-primary);
    margin-bottom: var(--spacing-sm);
  }
  
  .page-subtitle {
    color: var(--text-secondary);
    font-size: var(--font-size-lg);
  }
}

.filter-section {
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  margin-bottom: var(--spacing-lg);
}

.filter-container {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.filter-group {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  flex-wrap: wrap;
  
  .filter-label {
    min-width: 60px;
    font-weight: 500;
    color: var(--text-primary);
  }
  
  .filter-options {
    display: flex;
    gap: var(--spacing-sm);
    flex-wrap: wrap;
    flex: 1;
  }
}

.filter-actions {
  display: flex;
  justify-content: flex-end;
}

.search-section {
  margin-bottom: var(--spacing-lg);
}

.search-container {
  max-width: 500px;
  margin: 0 auto;
}

.result-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  
  .stats-text {
    color: var(--text-secondary);
  }
}

.novels-section {
  min-height: 400px;
}

.novels-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: var(--spacing-lg);
}

.novels-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.novel-item {
  display: flex;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--radius-lg);
  padding: var(--spacing-lg);
  cursor: pointer;
  transition: all 0.3s ease;
  
  &:hover {
    box-shadow: var(--shadow-lg);
    border-color: var(--primary-color);
  }
  
  .item-cover {
    position: relative;
    width: 80px;
    height: 100px;
    margin-right: var(--spacing-lg);
    flex-shrink: 0;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: var(--radius-md);
    }
    
    .vip-badge {
      position: absolute;
      top: -5px;
      right: -5px;
      background: var(--secondary-color);
      color: white;
      padding: 2px 6px;
      border-radius: var(--radius-sm);
      font-size: var(--font-size-xs);
      font-weight: bold;
    }
  }
  
  .item-content {
    flex: 1;
    margin-right: var(--spacing-lg);
    
    .item-title {
      font-size: var(--font-size-lg);
      font-weight: 600;
      color: var(--text-primary);
      margin-bottom: var(--spacing-xs);
      
      // 文本溢出处理
      display: -webkit-box;
      -webkit-line-clamp: 1;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .item-author {
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
      margin-bottom: var(--spacing-sm);
    }
    
    .item-desc {
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
      line-height: var(--line-height-normal);
      margin-bottom: var(--spacing-md);
      
      // 文本溢出处理
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
    }
    
    .item-tags {
      display: flex;
      gap: var(--spacing-xs);
      flex-wrap: wrap;
    }
  }
  
  .item-stats {
    width: 200px;
    flex-shrink: 0;
    
    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: var(--spacing-sm);
      font-size: var(--font-size-sm);
      
      .stat-label {
        color: var(--text-tertiary);
      }
      
      .stat-value {
        color: var(--text-secondary);
      }
    }
  }
}

.empty-state {
  text-align: center;
  padding: var(--spacing-xl);
}

.pagination-section {
  display: flex;
  justify-content: center;
  margin-top: var(--spacing-xl);
}

// 响应式设计
@media (max-width: 768px) {
  .library-page {
    padding: var(--spacing-md);
  }
  
  .filter-group {
    flex-direction: column;
    align-items: flex-start;
    
    .filter-label {
      min-width: auto;
    }
  }
  
  .result-stats {
    flex-direction: column;
    gap: var(--spacing-md);
  text-align: center;
}
  
  .novels-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: var(--spacing-md);
  }
  
  .novel-item {
    flex-direction: column;
    
    .item-cover {
      width: 100%;
      height: 200px;
      margin-right: 0;
      margin-bottom: var(--spacing-md);
    }
    
    .item-content {
      margin-right: 0;
      margin-bottom: var(--spacing-md);
    }
    
    .item-stats {
      width: 100%;
    }
  }
}</style> 